package c15;

/**
 * 同时开始
 */
public class RacerDemo {
    static class FireFlag {
        private volatile boolean fired = false;

        public synchronized void waitForFlag() {
            while (!fired) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public synchronized void fire() {
            this.fired = true;
            notifyAll();
        }
    }

    static class Racer extends Thread {
        FireFlag fireFlag;

        public Racer(FireFlag fireFlag) {
            this.fireFlag = fireFlag;
        }

        public void run() {
            this.fireFlag.waitForFlag();
            System.out.println("start run " + Thread.currentThread().getName());
        }

        public static void main(String[] args) {
            int num = 10;
            FireFlag flag = new FireFlag();
            Thread[] races = new Thread[num];
            for (int i = 0; i < num; i++) {
                races[i] = new Racer(flag);
                races[i].start();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("fire");
            flag.fire();
        }
    }
}
